﻿Ext.namespace('EHSubmit.Analysis');
Ext.namespace('EHSubmit.Analysis.List');
//////////////////////////////////////////////////////////////////////
// 某课程所有作业的 列模式
EHSubmit.Analysis.List.ColumnModel = new Ext.grid.ColumnModel([
    { header: '作业ID', hidden: true, hideable: false, dataIndex: 'ID' },
    { header: '作业名', width: 160, sortable: true, hidden: false, dataIndex: 'Title' },
    { header: '布置时间', width: 90, sortable: true, renderer: Ext.util.Format.dateRenderer('Y年m月d日'), dataIndex: 'PublishTime' }
/*    { header: '最后期限', width: 80, sortable: true, renderer: Ext.util.Format.dateRenderer('Y年m月d日'), dataIndex: 'DeadLine' },
    { header: '附件', width: 20, sortable: false, renderer: EHSubmit.Format.goalAttachRenderer, dataIndex: 'AttachPath' },
    { header: '说明', sortable: false, dataIndex: 'Description' }*/
]);

// 某课程所有作业的 数据源
EHSubmit.Analysis.List.DataStore = new Ext.data.Store({
    baseParams: { Op: 'List_Goals', courseID: '' },      // 需要传递操作参数  sid学生的ID
    proxy: new Ext.data.HttpProxy({ url: EHSubmit.ajaxRoot + 'GoalHandler.ashx' }),  //后台具体处理

    reader: new Ext.data.JsonReader({
            totalProperty: 'count',    //总记录个数
            root: 'goals',
            id: 'ID'
        },
        [   // 数据模型
            { name: 'ID' },
            { name: 'Title' },
            { name: 'PublishTime' }
/*            { name: 'DeadLine' },
            { name: 'AttachPath' },
            { name: 'Description' }*/
    ]),
    listeners: {
        load: function(thisStore, records, opt) {
            //图表切换
            var courseChart = Ext.getCmp('analysis_CourseChartPanel');
            courseChart.show();
            courseChart.getComponent('tipLabel').show();
            if(thisStore.getTotalCount() > 0){
                courseChart.getComponent('detailsButton').show();
            }
            else{
                courseChart.getComponent('detailsButton').hide();
            }
            Ext.getCmp('analysis_GoalChartPanel').hide();
        },
        /// 加载异常处理
        exception: function(proxy, type, action, options, response){
            Ext.MessageBox.alert('数据加载错误!','请与管理员联系');
            
        }
    }
});


EHSubmit.Analysis.CentralArea = {
    title: '统计信息',
    xtype:'panel',
    frame: true,
    //-----居中设置----
//    style: 'margin:0 auto',
//    width: 400,
//    labelAlign: 'left',
    
    //autoHeight:true,
    margins: '3 0 3 3',
    region: 'center',
    items: [{
        xtype:'form',
        id:'analysis_CourseChartPanel',
        labelWidth :1,
        //hideMode :'display',
        
        //plugins: new Ext.ux.plugin.VisibilityMode(),        
    
        items:[{
            xtype: 'columnchart',
            
	        plugins: new Ext.ux.plugin.VisibilityMode(),
            
            url: EHSubmit.extRoot + 'resources/charts.swf',
            id: 'analysis_course_chart',
            height: 400,
            xField: 'GoalName',
            xAxis: new Ext.chart.CategoryAxis({
                title: '作业名'
            }),
            yAxis: new Ext.chart.NumericAxis({
                title: '分数',
                displayName: '分数',
                minimum: 0,
                maximum: 100
                //labelRenderer : Ext.util.Format.numberRenderer('0,0')
            }),
            extraStyle: {
                xAxis: {
                    //labelRotation: -30
                }
            },

            tipRenderer: function(chart, record, index, series) {
                if (series.yField == 'Max') {
                    return record.data.GoalName + ' 最高分为' + record.data.Max;
                }
                else if (series.yField == 'Average') {
                    return record.data.GoalName + ' 平均分为' + record.data.Average;
                }
                else if ( series.yField == 'Min') {
                    return record.data.GoalName + ' 最低分为' + record.data.Min;
                }
                else{
                    return record.data.GoalName + ' 您的分数为' + record.data.myScore;
                }
            },

            store: new Ext.data.JsonStore({
                //autoDestroy: true,
                baseParams: { Op: 'course' },
                proxy: new Ext.data.HttpProxy({ url: EHSubmit.ajaxRoot + 'AnalysisHandler.ashx' }),  //后台具体处理
                root: 'data',
                fields: [
				    { name: 'GoalID', mapping: 'GoalID' },
				    { name: 'GoalName', mapping: 'GoalName' },
				    { name: 'Max', mapping: 'Max' },
				    { name: 'Min', mapping: 'Min' },
				    { name: 'Average', mapping: 'Average' },
				    { name: 'myScore', mapping: 'myScore'}
			    ]
            }),
            series: [{
                type: 'line',
                displayName: '最高分',
                yField: 'Max',
                style: {
                    color: 0x00FF00
                }
            }, {
                type: 'line',
                displayName: '平均分',
                yField: 'Average',
                style: {
                    color: 0x15428B
                }
            }, {
                type: 'line',
                displayName: '最低分',
                yField: 'Min',
                style: {
                    color: 0xFF0000
                }
            }, {
                type: 'line',
                displayName: '您的分数',
                yField: 'myScore',
                style: {
                    color: 0xFF7F00
                }
            }]
        },{
            xtype:'label',
            //width:400,
            autoWidth :true,
            hidden:true,
            itemId : 'tipLabel',
            text: '',
            fieldLabel:' ',
            labelSeparator:' ' 
        },{
            xtype:'button',
            itemId :'detailsButton',
            hidden:true,
            text:'查看详情',
            fieldLabel:' ',
            labelSeparator:' ' ,
            handler:function(){
            	EHSubmit.showWin(EHSubmit.Analysis.Details.WinConfig);
            }
        }]
    }, {
        xtype: 'form',
        id: 'analysis_GoalChartPanel',
        hidden:true,
        labelWidth :1,
        //hideMode :'display',
        
        //plugins: new Ext.ux.plugin.VisibilityMode(),
        
        items:[{
	        id: 'analysis_goal_chart',
	        xtype: 'piechart',
	        
	        plugins: new Ext.ux.plugin.VisibilityMode(),  //    <!-- 对于chart展示的bug的部分解决-->但关掉tab再生成tab时，问题仍然存在
	        
	        //hidden: true,
	        height: 400,
	        url: EHSubmit.extRoot + 'resources/charts.swf',
	        dataField: 'Total',
	        categoryField: 'Category',
	        store: new Ext.data.JsonStore({
                //autoDestroy: true,
	            baseParams: { Op: 'goal', goalID: '' },    
	            proxy: new Ext.data.HttpProxy({ url: EHSubmit.ajaxRoot + 'AnalysisHandler.ashx' }),  //后台具体处理
	            root: 'data',
	            fields: [
				    { name: 'Category', mapping: 'Category' },
				    { name: 'Total', mapping: 'Total' }
			    ]
	        }),
	        extraStyle:{
		        legend:{
			        display: 'bottom',
			        padding: 5,
			        font:{
				        family: 'Tahoma',
				        size: 13
				    }
			    }
		    }
        },{
            xtype:'label',
            itemId:'tipLabel',
            autoWidth :true,
            text: '',
            fieldLabel:' ',
            labelSeparator: ' '   
        }]     
    }]
}



EHSubmit.Analysis.EastArea = {
    title: '选择课程',
    frame: true,
    height: 400,
    width: 290,
    layout: 'form',
    margins: '3 3 3 -2',
    //---折叠后的margins
    cmargins: '3 3 3 3',
    split: true,
    region: 'east',
    collapsible: true,
    items: [{
        id: 'Analysis_CoursesCombo',
        xtype: 'combo',
        editable: false,
        width: 170,
        emptyText: '请选择...',
        fieldLabel: '请选择一门课程',
        mode: 'remote',
        triggerAction: 'all',
        selectOnFocus: true,
        valueField: 'courseID',
        displayField: 'courseName',

        /*  
        * 关键点(网上资料)
        * 1. x-menu使combo在选择的时候不会隐藏掉menu,看Ext.menu.MenuMgr.onMouseDown源码即知  
        * 2. x-menu里面的"z-index: 15000;",因为menu里面的layer的z-index是15000,则这里大于15000(需要限制覆盖原来的文档元素element.style)即可..   
        * 如果实际用x-menu，其他有应用x-menu的会受到干扰，设置还需考虑适当的值
        */
        listClass: 'x-menu',
        store: new Ext.data.JsonStore({
            storeId: 'courseStore',
            //autoLoad: true,
            baseParams: { Op: 'List_Course' },     //根据教师id获取其教的课程
            proxy: new Ext.data.HttpProxy({ url: EHSubmit.ajaxRoot + 'CourseHandler.ashx' }),  //后台具体处理

            root: 'courses',
            fields: [
				{ name: 'courseID', mapping: 'Id' },
				{ name: 'courseName', mapping: 'Name' }
			]
        }),

        listeners: {
            select: function(combo, record, index) {
                //---点击查看详细，查看详细情况用
                EHSubmit.Analysis.Details.courseID = record.data.courseID;
            
                //刷新右侧的grid
                var gridStore = Ext.getCmp('Analysis_WorkListGrid').getStore();
                gridStore.setBaseParam('courseID', record.data.courseID);     // 传递courseID
                gridStore.load();
                gridStore.sort('PublishTime', 'ASC');

                //刷新chart和label（有bug，关掉tab再打开会报错）
                var tp_chart = Ext.getCmp('analysis_course_chart');
                var store = tp_chart.store;
                store.setBaseParam('courseID', record.data.courseID);
                store.load();
                Ext.Ajax.request({
                    url: EHSubmit.ajaxRoot + 'GoalHandler.ashx',
                    params: {
                        Op: 'CountUnnormal',
                        courseID: record.data.courseID
                    },
                    success: function(response, opts) {

                        //获取服务器端的数据(解析后返回的是对象)
                        var statistics = Ext.decode(response.responseText).statistics;
                        var committed = statistics.total - statistics.Uncommitted;
                        var chartTip = Ext.getCmp('analysis_CourseChartPanel').getComponent('tipLabel');
                        var tips = '该课程总作业数为' + statistics.total + '次,在您已交的' + committed + '次作业中尚未打分的有' + statistics.Unmarked + '次,另外您还缺交了' + statistics.Uncommitted + '次!';
                        chartTip.setText(tips);
                        if(statistics.Unmarked > 0 || statistics.Uncommitted > 0){
                            Ext.getCmp('analysis_CourseChartPanel').getComponent('detailsButton').show();
                        }
                        else{
                            Ext.getCmp('analysis_CourseChartPanel').getComponent('detailsButton').hide();
                        }
                    }
                    //      failure: function(response, opts){
                    //          var result = Ext.decode(response.responseText).msg;
                    //          Ext.MessageBox.alert('错误',result);
                    //      },
                });
            }
        }
    }, {
        //****************************显示已上交的作业列表*****************
        xtype: 'grid',
        id: 'Analysis_WorkListGrid',
        loadMask: true,          // 加载数据时遮住
        frame: false,
        layout: 'fit',
        //border:true,
        height: 372,
        cm: EHSubmit.Analysis.List.ColumnModel,
        ds: EHSubmit.Analysis.List.DataStore,
        sm: new Ext.grid.RowSelectionModel({
            singleSelect: true
        }),
        listeners: {
            cellclick: function(thisGrid, rowIndex, columnIndex, e) {
                //---图表切换---------
                Ext.getCmp('analysis_CourseChartPanel').hide();
                Ext.getCmp('analysis_GoalChartPanel').show();

                //--刷新图表和label
                var store = Ext.getCmp('analysis_goal_chart').store;
                var goalID = thisGrid.getStore().getAt(rowIndex).data.ID;
                store.setBaseParam('goalID', goalID);
                store.load();
                Ext.Ajax.request({
                    url: EHSubmit.ajaxRoot + 'AnalysisHandler.ashx',
                    params: {
                        Op: 'LevelConfirm',
                        goalID: goalID
                    },
                    success: function(response, opts) {

                        //获取服务器端的数据(解析后返回的是对象)
                        var reply = Ext.decode(response.responseText).reply;
                        var chartTip = Ext.getCmp('analysis_GoalChartPanel').getComponent('tipLabel');
                        
                        chartTip.setText(reply);

                    }
                })
            },
            delay: 10   // allow rows to be rendered
        }
}]
    }
			
//    }
//}

//-------容器--------------
EHSubmit.Analysis.Tab = {
    id: 'analysisForm',
    title: '统计分析',
    layout: 'border',
    frame: false,
    border:false,
    closable: true,
    //plain:false,
    //bodyStyle: 'padding:5px;',
    items: [EHSubmit.Analysis.CentralArea,EHSubmit.Analysis.EastArea],
    
    listeners:{
//        activate:function(){
//            alert('ac');
//        },
        //--界面初始化------
        render:function(){
            var courseChartPanel = Ext.getCmp('analysis_CourseChartPanel');
            courseChartPanel.show();
            courseChartPanel.getComponent('tipLabel').hide();
            courseChartPanel.getComponent('detailsButton').hide();
            Ext.getCmp('analysis_GoalChartPanel').hide();
            //表格和图的store的清除
            var courseChart = Ext.getCmp('analysis_course_chart');
            courseChart.store.removeAll();
            Ext.getCmp('Analysis_WorkListGrid').store.removeAll();
            //alert('asd');
        }
//        tabchange:function(){
//            alert('tc');
//        }
    }
};

///////////////////////////////////////////////////////
/////////////////////////////////////////////////////
Ext.namespace('EHSubmit.Analysis.Details');

EHSubmit.Analysis.Details.ColumnModel = new Ext.grid.ColumnModel([
    { header: '作业ID', hidden: true, hideable: false, dataIndex: 'ID' },
    { header: '作业名', width: 160, sortable: true, hidden: false, dataIndex: 'Title' },
    { header: '布置时间', width: 90, sortable: true, renderer: Ext.util.Format.dateRenderer('Y年m月d日'), dataIndex: 'PublishTime' },
    { header: '最后期限', width: 90, sortable: true, renderer: Ext.util.Format.dateRenderer('Y年m月d日'), dataIndex: 'DeadLine' },
    { header: '情况说明', width: 90,sortable: true, dataIndex: 'Description' }
]);

// 某课程所有作业的 数据源
EHSubmit.Analysis.Details.DataStore = new Ext.data.GroupingStore({
    baseParams: { Op: 'ListUnnormal', courseID: '' },      // 需要传递操作参数  sid学生的ID
    proxy: new Ext.data.HttpProxy({ url: EHSubmit.ajaxRoot + 'GoalHandler.ashx' }),  //后台具体处理
    sortInfo:{field: 'Description', direction: "ASC"},
    groupField:'Description',

    reader: new Ext.data.JsonReader({
            totalProperty: 'count',    //总记录个数
            root: 'goals',
            id: 'ID'
        },
        [   // 数据模型
            { name: 'ID' },
            { name: 'Title' },
            { name: 'PublishTime' },
            { name: 'DeadLine' },
            { name: 'Description' }
    ]),
    listeners: {
        /// 加载异常处理
        exception: function(proxy, type, action, options, response){
            Ext.MessageBox.alert('数据加载错误!','请与管理员联系');
            
        }
    }
});



EHSubmit.Analysis.Details.GridPanel = {
	xtype:'grid',
	id:'Analysis_UnnormalGrid',
	loadMask: true,          // 加载数据时遮住
	frame: true,
	height: 300,
	cm: EHSubmit.Analysis.Details.ColumnModel,
	ds: EHSubmit.Analysis.Details.DataStore,
	sm: new Ext.grid.RowSelectionModel({
		singleSelect: true
	}),
	
    view: new Ext.grid.GroupingView({
        forceFit:true,
        groupTextTpl: '{text} ({[values.rs.length]} {["次"]})'
    }),
    
	buttons:[{
		text:'确定',
		handler: function(){
			EHSubmit.closeWin(EHSubmit.Analysis.Details.WinConfig);
		}
	}]
}   //end of grid


EHSubmit.Analysis.Details.WinConfig ={
	id: 'detailsWindow',
	xtype: 'window',
	width: 550,
	height: 450,
	//plain: true,
	border: true,
	layout: 'fit',
	modal: true,
	title: '未交作业和未评分作业详情',
	frame: true,
	items:EHSubmit.Analysis.Details.GridPanel,

	listeners:{
		activate: function(){
			var store = Ext.getCmp('Analysis_UnnormalGrid').getStore();
			store.setBaseParam('courseID',EHSubmit.Analysis.Details.courseID);
            store.load();
		}	
	}
	
}